package com.example.guiguiapplicatio;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.guiguiapplicatio.api.Interface.AllCallback;
import com.example.guiguiapplicatio.api.PostImgApi;
import com.example.guiguiapplicatio.Response.ServicePackageResponse;
import com.example.guiguiapplicatio.Response.SigningAdd;
import com.example.guiguiapplicatio.utils.PreferencesUtil;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.ArrayList;

import cn.refactor.lib.colordialog.PromptDialog;

public class NewFileNextActivity extends AppCompatActivity implements
        View.OnClickListener {

    private final int INSPECTED_CODE = 1; // 被检查人签名意图代码
    private final int INSPECTOR_CODE = 2; // 检查人签名意图代码
    private ImageView stakeholdersSignImageView, beneficiarySignImageView;
    private PostImgApi postImgApi;
    private Button confirmTheContract;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_new_file_next);
        EditText beneficiary_editText = findViewById(R.id.beneficiary_et);
        EditText beneficiary_phone_editText = findViewById(R.id.et_beneficiary_phone);
        EditText data_editText = findViewById(R.id.data_et);
        beneficiary_editText.setText(PreferencesUtil.getString(this,"beneficiary_name"));
        beneficiary_phone_editText.setText(PreferencesUtil.getString(this,"beneficiary_telephone"));
        data_editText.setText(PreferencesUtil.getString(this,"startSigningDate") + "-" + PreferencesUtil.getString(this,"endSigningDate"));
        stakeholdersSignImageView = findViewById(R.id.stakeholders_sign_image_view);  // 被检查单位（人）签名
        beneficiarySignImageView = findViewById(R.id.beneficiary_sign_image_view);  // 检查人签名
        confirmTheContract = findViewById(R.id.confirm_the_contract);
        // 设置监听器confirm_the_contract
        stakeholdersSignImageView.setOnClickListener(this);    // 获取被检查单位（人）签字
        beneficiarySignImageView.setOnClickListener(this);
        confirmTheContract.setOnClickListener(this);
    } // onCreate-end
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.stakeholders_sign_image_view) {  // 被检查单位（人）签名
            Intent intent = new Intent(this, SignatureActivity.class);
            startActivityForResult(intent, INSPECTED_CODE); // 获取被检查单位（人）手写签名
        } else if (v.getId() == R.id.beneficiary_sign_image_view) {  // 被检查人签名
            Intent intent = new Intent(this, SignatureActivity.class);
            startActivityForResult(intent, INSPECTOR_CODE);  // 获取检查人手写签名
        }else if (v.getId() == R.id.confirm_the_contract) {  // 被检查人签名
            View confirmButton = findViewById(R.id.confirm_the_contract);
            confirmButton.setVisibility(View.GONE);
            View ve = getWindow().getDecorView();
            Bitmap bitmap = Bitmap.createBitmap(ve.getWidth(), ve.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas();
            canvas.setBitmap(bitmap);
            ve.draw(canvas);
            Gson gson = new Gson();
            String packageResponseListJson = getIntent().getStringExtra("packageResponseList");
            Type listType = new TypeToken<ArrayList<ServicePackageResponse>>(){}.getType();
            ArrayList<ServicePackageResponse> packageResponseList = gson.fromJson(packageResponseListJson, listType);
            postImgApi = new PostImgApi(new AllCallback() {
                @Override
                public void onSuccess(ResponseBody<Object> responseBody) throws ParseException {
                    if(responseBody.getCode() == 200){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new PromptDialog(NewFileNextActivity.this)
                                        .setDialogType(PromptDialog.DIALOG_TYPE_INFO)
                                        .setAnimationEnable(true)
                                        .setTitleText("INFO")
                                        .setContentText("签约成功返回首页")
                                        .setPositiveListener("OK", new PromptDialog.OnPositiveListener() {
                                            @Override
                                            public void onClick(PromptDialog dialog) {
                                                Intent intent = new Intent(NewFileNextActivity.this, MainActivity.class);
                                                intent.putExtra("id",1);
                                                startActivity(intent);
                                                dialog.dismiss();
                                            }
                                        }).show();
                            }
                        });
                    }
                    else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new PromptDialog(NewFileNextActivity.this)
                                        .setDialogType(PromptDialog.DIALOG_TYPE_WRONG)
                                        .setAnimationEnable(true)
                                        .setTitleText("WRONG")
                                        .setContentText("签约失败")
                                        .setPositiveListener("OK", new PromptDialog.OnPositiveListener() {
                                            @Override
                                            public void onClick(PromptDialog dialog) {
                                                dialog.dismiss();
                                            }
                                        }).show();
                            }
                        });
                    }
                }

                @Override
                public void onFailure(String errorMessage) {

                }
            });
            postImgApi.performPostImg(bitmap,"/storage/emulated/0/Download/image.jpg",new SigningAdd(PreferencesUtil.getString(this,"beneficiary_id"),PreferencesUtil.getInt(this,"doctor_id"),PreferencesUtil.getString(this,"startSigningDate"),PreferencesUtil.getString(this,"endSigningDate")),packageResponseList);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (intent != null && resultCode == Activity.RESULT_OK && requestCode == INSPECTED_CODE) {
            // 取回被检查单位（人）手写签名
            byte[] bytes = intent.getByteArrayExtra("bitmapbytes");
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            stakeholdersSignImageView.setImageBitmap(bitmap);
        } else if (intent != null && resultCode == Activity.RESULT_OK && requestCode == INSPECTOR_CODE) {
            // 取回检查人手写签名
            byte[] bytes = intent.getByteArrayExtra("bitmapbytes");
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            beneficiarySignImageView.setImageBitmap(bitmap);
        }
    }
}
